using System.Web.UI;
using System.Web.UI.WebControls;

namespace OpenWaves.Web.Controls
{
    [ParseChildren(true)]
    public class OptionalContentWithFallbackPlaceholder : Control
    {
        private object dataItem;
        public object DataItem
        {
            get { return this.dataItem; }
            set
            {
                this.dataItem = value;
                this.ShowContent = value != null;
            }
        }

        protected bool ShowContent
        {
            get { return (bool?)this.ViewState["ShowContent"] ?? true; }
            set { this.ViewState["ShowContent"] = value; }
        }

        private readonly PlaceHolder content = new PlaceHolder();
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public PlaceHolder Content
        {
            get { return this.content; }
        }

        private readonly PlaceHolder fallbackContent = new PlaceHolder();
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public PlaceHolder FallbackContent
        {
            get { return this.fallbackContent; }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            var activeContent = this.ShowContent ? this.Content : this.FallbackContent;
            this.Controls.Add(activeContent);
        }

        protected override void OnDataBinding(System.EventArgs e)
        {
            this.Controls.Clear();

            base.OnDataBinding(e);

            var activeContent = this.ShowContent ? this.Content : this.FallbackContent;
            
            this.Controls.Add(activeContent);

            activeContent.DataBind();
            this.ChildControlsCreated = true;
        }
    }
}